package com.dkd.easybook.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.dkd.common.utils.EbUtils;
import com.dkd.easybook.service.impl.EbIconsServiceImpl;
import com.dkd.easybook.tools.EbTools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.easybook.domain.EbIcons;
import com.dkd.easybook.service.IEbIconsService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;
import com.dkd.common.utils.file.MimeTypeUtils;

import static com.dkd.framework.datasource.DynamicDataSourceContextHolder.log;
/**
 * 用户图标Controller
 *
 * @author itheima
 * @date 2024-12-12
 */
@Api(tags = "用户图标Controller")
@RestController
@RequestMapping("/easybook/icons")
public class EbIconsController extends BaseController {
    @Autowired
    private IEbIconsService ebIconsService;
    @Autowired
    private EbIconsServiceImpl ebIconsServiceImpl;
    /**
     * 查询用户图标列表
     */
    @ApiOperation("查询用户图标列表")
    @PreAuthorize("@ss.hasPermi('easybook:icons:list')")
    @GetMapping("/list")
    public TableDataInfo list(EbIcons ebIcons) {
        startPage();
        List<EbIcons> list = ebIconsService.selectEbIconsList(ebIcons);
        return getDataTable(list);
    }
    @ApiOperation("查询用户图标列表")
    @PreAuthorize("@ss.hasPermi('easybook:icons:list')")
    @PostMapping("/listByIds")
    public TableDataInfo listByIds(@RequestBody List<Long> ids) {
        startPage();
        List<EbIcons> list = ebIconsService.listByIds(ids);
        return getDataTable(list);
    }
    /**
     * 导出用户图标列表
     */
    @ApiOperation("导出用户图标列表")
    @PreAuthorize("@ss.hasPermi('easybook:icons:export')")
    @Log(title = "用户图标", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EbIcons ebIcons) {
        List<EbIcons> list = ebIconsService.selectEbIconsList(ebIcons);
        ExcelUtil<EbIcons> util = new ExcelUtil<EbIcons>(EbIcons.class);
        util.exportExcel(response, list, "用户图标数据");
    }
    /**
     * 获取用户图标详细信息
     */
    @ApiOperation("获取用户图标详细信息")
    @PreAuthorize("@ss.hasPermi('easybook:icons:query')")
    @GetMapping(value = "/{iconId}")
    public AjaxResult getInfo(@PathVariable("iconId") Long iconId) {
        return success(ebIconsService.selectEbIconsByIconId(iconId));
    }
    /**
     * 新增用户图标
     */
    @ApiOperation("新增用户图标")
    @PreAuthorize("@ss.hasPermi('easybook:icons:add')")
    @Log(title = "用户图标", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EbIcons ebIcons) {
        return toAjax(ebIconsService.insertEbIcons(ebIcons));
    }
    /**
     * 修改用户图标
     */
    @ApiOperation("修改用户图标")
    @PreAuthorize("@ss.hasPermi('easybook:icons:edit')")
    @Log(title = "用户图标", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EbIcons ebIcons) {
        return toAjax(ebIconsService.updateById(ebIcons));
    }
    /**
     * 删除用户图标
     */
    @ApiOperation("删除改用户图标")
    @PreAuthorize("@ss.hasPermi('easybook:icons:remove')")
    @Log(title = "用户图标", businessType = BusinessType.DELETE)
    @DeleteMapping("/{iconIds}")
    public AjaxResult remove(@PathVariable Long[] iconIds) {
        return toAjax(ebIconsService.deleteEbIconsByIconIds(iconIds));
    }
    //批量插入系统图标
    @ApiOperation("批量插入系统图标")
    @PreAuthorize("@ss.hasPermi('easybook:icons:add')")
    @Log(title = "用户图标", businessType = BusinessType.INSERT)
    @PostMapping("/batchAddSysIcons")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult batchAddSysIcons() throws Exception {
        String directoryPath = "D:\\DevProject\\code-all-by-lwh\\easy-book-service\\attachment\\defaultAccountIcon";
        File directory = new File(directoryPath);
        if (!directory.exists() || !directory.isDirectory()) {
            throw new IllegalArgumentException("指定的路径不是一个有效的目录");
        }
        File[] files = directory.listFiles();
        if (files == null || files.length == 0) {
            log.info("目录中没有文件");
            throw new Exception("错误");
        }
        List<EbIcons> iconsToInsert = new ArrayList<>();
        for (File file : files) {
            if (file.isFile()) {
                EbIcons ebIcons = new EbIcons();
                ebIcons.setSize(file.length());
                ebIcons.setFileName(file.getName());
                ebIcons.setContentType(MimeTypeUtils.IMAGE_SVG);
                ebIcons.setExt(MimeTypeUtils.getExtension(file.getName()));
                ebIcons.setUrl("/profile/defaultAccountIcon/" + file.getName());
                EbUtils.setUserIdIfNull(ebIcons, EbIcons::getUserId, EbIcons::setUserId);
                iconsToInsert.add(ebIcons);
            }
        }
        if (!iconsToInsert.isEmpty()) {
            boolean result = ebIconsServiceImpl.saveBatch(iconsToInsert);
            if (result) {
                log.info("图标插入成功，共插入 {} 个图标", iconsToInsert.size());
            } else {
                log.error("图标插入失败");
            }
        }
        return AjaxResult.success();
    }
}
